//
//  AliyunOSSDemo.m
//  OSS上传
//
//  Created by edison on 2017/6/7.
//  Copyright © 2017年 edison. All rights reserved.
//

#import "LCAliyunOSS.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AFNetworking.h>


//NSString * const ossEndPoint = @"https://oss-cn-qingdao.aliyuncs.com";
//NSString * const ossAccesskey = @"LTAI5tMPAk2ZoybUE2fUs3mc";
//NSString * const ossAccessSecret = @"7RuHEYeqCBBzm4nPldAO03diRcpC38";
//NSString * const ossDomain = @"https://jubo-app-test.oss-cn-qingdao.aliyuncs.com";
//NSString * const ossBucketName = @"jubo-app-test";

NSString * const ossEndPoint = @"https://oss-cn-qingdao.aliyuncs.com";
NSString * const ossAccesskey = @"LTAI5tMPAk2ZoybUE2fUs3mc";
NSString * const ossAccessSecret = @"7RuHEYeqCBBzm4nPldAO03diRcpC38";
NSString * const ossDomain = @"https://jubo-app-prod.oss-cn-qingdao.aliyuncs.com";
NSString * const ossBucketName = @"jubo-app-prod";

OSSClient * client;

@interface LCAliyunOSS ()
//获取token返回的json数据
@property(nonatomic,strong)NSDictionary *responseObject;
@property (assign, nonatomic) int age;
@end

@implementation LCAliyunOSS

#pragma mark ====创建上传的单例====
+ (instancetype)sharedInstance {
    static LCAliyunOSS *instance;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        instance = [LCAliyunOSS new];
    });
    
    return instance;
}


#pragma mark ===开启上传环境====
- (void)setupEnvironment {
    // 打开调试log
    [OSSLog enableLog];
    
    // 初始化sdk
    [self initOSSClient];
    }

#pragma maek ===  初始化阿里云sdk====
- (void)initOSSClient {
    
    // 明文设置AccessKeyId/AccessKeySecret的方式建议只在测试时使用LTAIUqUzNn0NgLQn   p5dgVPGj39s4TBizt9axFWcgg9Nacr
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:ossAccesskey secretKey:ossAccessSecret];
//    client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
      
//    //网络配置
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    
    conf.maxRetryCount = 1; // 网络请求遇到异常失败后的重试次数
    conf.timeoutIntervalForRequest = 60; // 网络请求的超时时间
    conf.timeoutIntervalForResource = 60; // 允许资源传输的最长时间
    
    client = [[OSSClient alloc] initWithEndpoint:ossEndPoint credentialProvider:credential clientConfiguration:conf];
}


#pragma mark ==== 同步上传=====
- (void)uploadObjectAsyncWith:(NSData *)uploadData withObjectKey:(NSString *)objectKey andUploadedUrl:(transferInfoValue)transfer {
    
    //上传请求类
    OSSPutObjectRequest * request = [OSSPutObjectRequest new];
    //文件夹名 后台给出
    request.bucketName = ossBucketName;
    //objectKey为文件名 一般自己拼接
    
    
//    此处修改 添加了上传文件格式 有时候会一直请求
    request.contentType =  @"application/octet-stream";
    
    NSString *imageName = [NSString stringWithFormat:@"app/%@/%@%@%@",[ZZPUtils getTimeFromShortTimeDa:[NSDate date]],userInfoId,[self getNowTimeTimestamp],objectKey];
    
    request.objectKey = imageName;

    //上传数据类型为NSData
    request.uploadingData = uploadData;
    
    request.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
          // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
    };
    
    OSSTask * putTask = [client putObject:request];
    [putTask continueWithBlock:^id(OSSTask *task) {
        
        if (!task.error) {
            
            //每次上传完一个文件都要回调
            NSLog(@"上传成功!");
            transfer([NSString stringWithFormat:@"%@/%@",ossDomain,imageName]);
        } else {
        
            transfer(@"");
           
        }
        return nil;
    }];
    
    //同步上传（去掉就是异步）因为我上传的文件有多种包括音视频,图片。而且OSS这边是每上传成功一个文件都要回调一次。比如我成功上传5张图片，那么就要回调5次。所以这个时候我就无法判断文件是否都上传完成。所以我就把这些上传的文件放在调度组里面，这样所有文件上传成功后我这边就知道了。如果上传放在调度组里，那么这里的同步上传就必须加上。
    [putTask waitUntilFinished];
}



- (void)uploadImagesAsyncWith:(NSArray *)uploadDataArray andUploadedUrl:(transferImagesValue)transfer {
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = uploadDataArray.count;
    NSMutableArray *callBackNames = [NSMutableArray array];
     int i = 0;
     for (NSData *image in uploadDataArray) {
         if (image) {
             NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                 //任务执行
                 OSSPutObjectRequest * put = [OSSPutObjectRequest new];
                 put.bucketName = ossBucketName;
                 NSString *imageName = [NSString stringWithFormat:@"app/%@/%@%@%d.png",[ZZPUtils getTimeFromShortTimeDa:[NSDate date]],userInfoId,[self getNowTimeTimestamp],i];
                 put.objectKey = imageName;
                 
                 put.uploadingData = image;
                 
                 OSSTask * putTask = [client putObject:put];
                 [putTask waitUntilFinished]; // 阻塞直到上传完成
                 if (!putTask.error) {
                     NSLog(@"upload object success!");
                     [callBackNames addObject:[NSString stringWithFormat:@"%@/%@",ossDomain,imageName]];
                 } else {
                     NSLog(@"upload object failed, error: %@" , putTask.error);
                     if (transfer) {
                         transfer([NSArray array]);
                     }
                     return;
                 }
                 if (image == uploadDataArray.lastObject) {
                     NSLog(@"upload object finished!");
                     if (transfer) {
                         transfer(callBackNames);
                     }
                 }
             }];
             if (queue.operations.count != 0) {
                 [operation addDependency:queue.operations.lastObject];
             }
             [queue addOperation:operation];
         }
         i++;
     }
}



- (NSString *)getNowTimeTimestamp{

    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];

    return timeSp;
}

@end
